package game.module.ddz.processor;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.ddz.bean.DdzRound;
import game.module.ddz.logic.DdzDataManager;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageDdz.C2SDdzChat;
import lua.LuaMessageDdz.PushDdzChat;
import lua.LuaMessageDdz.S2CDdzChat;
import lua.LuaMessageLogin.S2ErrorCode;

@MsgCodeAnn(msgcode = C2SDdzChat.id, accessLimit = 1000)
public class DdzChatProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(DdzChatProcessor.class);

	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw request) throws Exception {
		C2SDdzChat reqMsg = C2SDdzChat.parse(request);
		byte msg_index = reqMsg.msg_index;
		int playerId = playingRole.getId();
		logger.info("ddz chu pai,playerId={},msg_index={}", playerId, msg_index);
		// 房间是否存在
		DdzRound ddzRound = DdzDataManager.getInstance().getDdzRoom(playerId);
		if (ddzRound == null) {
			S2ErrorCode respMsg = new S2ErrorCode(201);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// do
		S2CDdzChat retMsg = new S2CDdzChat();
		playingRole.writeAndFlush(retMsg.build(playingRole.alloc()));
		// push
		int player_index = ddzRound.getPlayerIds().indexOf(playerId);
		PushDdzChat pushMsg = new PushDdzChat((byte) player_index, msg_index);
		List<Integer> playerIds = ddzRound.getPlayerIds();
		for (Integer aPlayerId : playerIds) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
			}
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

}
